package cn.z2huo.demo.jakarta.validation.handler;

import cn.z2huo.core.status.StatusCode;
import cn.z2huo.core.web.ResponseMessage;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestValueException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>
 *
 * @author z2huo
 */
@RestControllerAdvice(value = {"cn.z2huo.demo.jakarta.validation.controller"})
public class ValidExceptionHandler {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class, MissingRequestValueException.class, MissingServletRequestParameterException.class})
    public ResponseMessage hanlder(MethodArgumentNotValidException e) {
        StringBuilder statusText = new StringBuilder();
        BindingResult bindResult = e.getBindingResult();
        if (bindResult.hasErrors()){
            bindResult.getFieldErrors().forEach(x -> {
                statusText.append(x.getDefaultMessage());
                statusText.append("; ");
            });
        }
        return new ResponseMessage().setSuccess(false)
                .setContent(statusText.toString())
                .setCode(StatusCode.CLIENT_ERROR.getCode());
    }

}
